package com.ruoyi.gateway.handler;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.ruoyi.common.core.exception.CaptchaException;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @name: MerchantValidateCodeHandler
 * @author: zhangzhimin
 * @date: 2025-05-13 11:56
 **/
@Component
public class MerchantValidateCodeHandler implements HandlerFunction<ServerResponse> {
    @Autowired
    private RedisService redisService;
    @Override
    public Mono<ServerResponse> handle(ServerRequest request) {
        AjaxResult ajax;
        try
        {
            Optional<String> phone = request.queryParam("phone");
            if(phone.get().isEmpty()){
                return Mono.error(new CaptchaException("验证码发送失败-->手机号码为空"));
            }
            String s = phone.get();
            System.out.print("得到的手机号"+s);

            Map<String, Object> map = new HashMap<>();
            // 创建一个宽 200 像素、高 100 像素、包含 4 个字符、15 条干扰线的圆圈验证码
            CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 15);
            // 获取验证码的内容
            String code = captcha.getCode();
            // 获取验证码图片的 Base64 编码
            String imageBase64 = captcha.getImageBase64();
redisService.setCacheObject(s,code,(long)60, TimeUnit.SECONDS);

            map.put("image", imageBase64);
//SMSUtil.send(s,"code:"+code);
            ajax = new AjaxResult(200, "验证码发送成功", map);

        }
        catch (CaptchaException e)
        {
            return Mono.error(e);
        }

        System.out.print("发送验证码2");
        return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(ajax));
    }
}
